package com.onpositive.datacollection.editor;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;

import com.onpositive.data.kvstorage.DataCollectionInfo;
import com.onpositive.data.kvstorage.DataCollectionStorer;
import com.onpositive.datacollection.proxy.RemoteDataCollection;
import com.onpositive.semantic.model.api.labels.IHasPresentationObject;
import com.onpositive.semantic.model.ui.generic.widgets.ISelectorElement;
import com.onpositive.semantic.model.ui.property.editors.structured.ListEnumeratedValueSelector;
import com.onpositive.semantic.ui.workbench.elements.XMLView;

public class GlobalExplorer extends XMLView {

	static DataCollectionInfo currentInfo;

	public GlobalExplorer() {
		super("collections.dlf");
	}
	
	
	public void saveCollection(){
		ISelectorElement element = (ISelectorElement) getElement("collection");
		DataCollectionInfo d=(DataCollectionInfo) element.getViewerSelection().getFirstElement();
		RemoteDataCollection collection = DataCollectionAcess.getCollection(d.getName());
		FileDialog dlg=new FileDialog(Display.getCurrent().getActiveShell(),SWT.SAVE);
		String open = dlg.open();
		if(open!=null){
			try {
				new DataCollectionStorer().downloadDataCollection(collection, new BufferedOutputStream(new FileOutputStream(open)));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void activate(){
		ListEnumeratedValueSelector element = (ListEnumeratedValueSelector) getElement("collection");
		Object firstElement = element.getViewerSelection().getFirstElement();
		if (firstElement instanceof IHasPresentationObject){
			IHasPresentationObject m=(IHasPresentationObject) firstElement;
			firstElement=m.getElement();
		}
		currentInfo = (DataCollectionInfo) firstElement;
		RemoteDataCollection collection = DataCollectionAcess.getCollection(currentInfo.getName());
		DataCollectionAcess.setCollection(collection);
		element.getBinding().refresh();
		element.getViewer().getControl().redraw();
	}
}
